<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\BaseAdminController;
use think\facade\View;
use think\facade\Request;
use app\system\model\LogOperate as Log;
use think\facade\Cookie;
use RobThree\Auth\TwoFactorAuth;
use RobThree\Auth\Providers\Qr\BaconQrCodeProvider;

class Profile extends BaseAdminController
{
    /**
     * 修改密码操作
     */
    private function updatePassword()
    {
        $old = input('old');
        $password = input('password');
        $check = input('check');
        if ($password !== $check) {
            return json(['msg' => '两次密码不一致']);
        }
        if (!password_verify($old, $this->user->password)) {
            return json(['msg' => '原密码错误']);
        }
        $this->user->password = password_hash($password, PASSWORD_DEFAULT);
        $this->user->save();
        Log::add('修改密码', [
            'ID' => UID,
            '昵称' => USERNAME,
        ]);
        Cookie::delete('auth');
        return json(['msg' => '']);
    }

    /**
     * 修改密码页面
     */
    public function password()
    {
        if (Request::isAjax()) {
            return $this->updatePassword();
        }
        View::assign('title', '修改密码');
        return View::fetch();
    }

    /**
     * 开启二步验证页面
     */
    public function auth()
    {
        $tfa = new TwoFactorAuth(new BaconQrCodeProvider());
        if (Request::isAjax()) {
            // 保存二步验证密钥
            $code = input('code');
            $secret = input('secret');
            $result = $tfa->verifyCode($secret, $code);
            if (!$result) {
                return json(['msg' => '验证码验证失败']);
            }
            $this->user->totp = $secret;
            $this->user->save();
            Log::add('开启二步验证', [
                'ID' => UID,
                '昵称' => USERNAME,
            ]);
            return json(['msg' => '']);
        }
        View::assign('title', '二步验证');
        View::assign('auth', $this->user->totp);
        if (empty($this->user->totp)) {
            // 生成二步验证密钥
            $secret = $tfa->createSecret();
            $image = $tfa->getQRText(USERNAME, $secret);
            View::assign('secret', $secret);
            View::assign('image', $image);
        }
        return View::fetch();
    }

    /**
     * 关闭二步验证操作
     */
    public function close()
    {
        $tfa = new TwoFactorAuth(new BaconQrCodeProvider());
        $code = input('code');
        $result = $tfa->verifyCode($this->user->totp, $code);
        if (!$result) {
            return json(['msg' => '验证码验证失败']);
        }
        $this->user->totp = '';
        $this->user->save();
        Log::add('关闭二步验证', [
            'ID' => UID,
            '昵称' => USERNAME,
        ]);
        return json(['msg' => '']);
    }
}
